package harnesses;
import static org.junit.Assert.*;

import java.util.Random;

import caches.Cache;

import counters.AtomicCounter;

public abstract class ConcurrentCacheHarness extends ConcurrentHarness {
	static private int RANGE = 1000;
	
	protected Cache<Long, Long> cache = initCache();
	protected Random random = new Random();
	protected AtomicCounter cacheHits = new AtomicCounter();
	protected AtomicCounter misHits = new AtomicCounter();

	protected abstract Cache<Long, Long> initCache();

	@Override
	protected Runnable newTask() {
		return new Runnable() {	public void run() {
				Long k = new Long(random.nextInt(RANGE));
				Long v = new Long(k.longValue());
				Long valueFromCache = cache.get(k);
				if (valueFromCache != null) {
					cacheHits.increment();
					if (!valueFromCache.equals(v))
						misHits.increment();
				}
				cache.put(k, v);
			} 
		};
	}
	
	@Override
	protected void checkResults() {
		System.out.printf("Cache hits = %d%n", cacheHits.getCounter());
		System.out.printf("errors = %d%n", misHits.getCounter());
		assertEquals(0, misHits.getCounter());		
	}

}
